<template>
  <div  class="CAD">
    <div id='CAD' style="width:100%;height: 100%;"></div>
  </div>
</template>

<script setup>
import {storeToRefs} from 'pinia'
import {useFontsStore} from '/@/stores/fonts'
  import opentype from 'opentype.js'
  import svgPanZoom from 'svg-pan-zoom';
  import * as makerjs from 'makerjs';
  import { onBeforeMount, onMounted, ref, watch, defineProps,inject } from 'vue';
  let props = defineProps(['propsObj'])
  let loadingCad = ref(false)
  let model = ref({})
 
let {fonts} = storeToRefs(useFontsStore())
  class rectangleBox {
    constructor({ width, height, point, text1,index }) {

     let y = 8
     let str1 = `${-width/2},${y},${-width/2 + 3},${y+1},${-width/2 + 3},${(y-1)}`
     let str2 = `${width/2},${y},${width/2 - 3},${y+1},${width/2 - 3},${(y-1)}`
     let str3 = `${width/2 +y },${height},${(width/2 +y) - 1},${height - 3},${width/2 +y + 3 - 2},${(height - 3)}`
     let str4 = `${width/2 +y},${0},${(width/2 +y) - 1},${0 + 3},${width/2 +y + 1},${(0 + 3)}`
      this.paths = {
        "h1":new makerjs.paths.Line([-width/2,y], [width/2,y]),
        "w1":new makerjs.paths.Line([width/2 +y,0], [width/2+y,height]),
        "w1_1":new makerjs.paths.Line([width/2 +y - 4,0], [width/2+y + 4,0]),
        "w1_2":new makerjs.paths.Line([width/2+y - 4,height], [width/2+y + 4,height]),
      }
      this.models = {
      
        outer: makerjs.model.move(new makerjs.models.Rectangle(width, height), [-width / 2, 0]),
        textW: makerjs.model.move(new makerjs.models.Text(fonts.value, `w=${width * 100}`, 3), [0, 1]),
        textH: makerjs.model.move(new makerjs.models.Text(fonts.value, `h=${height * 100}`, 3), [width / 2 + y + 1, height / 2]),
        text_1: makerjs.model.move(new makerjs.models.Text(fonts.value, `${text1}`, 3), [width / 2 - (text1.length), 1]),
       
        Ar1:new makerjs.models.ConnectTheDots(true, str1),
        Ar2:new makerjs.models.ConnectTheDots(true, str2),

        Ar3:new makerjs.models.ConnectTheDots(true, str3),
        Ar4:new makerjs.models.ConnectTheDots(true, str4),
      }
      this.models.outer.layer='layer3'
      this.models.Ar1.layer = 'layer1'
      this.models.Ar2.layer = 'layer1'
      this.models.Ar3.layer = 'layer2'
      this.models.Ar4.layer = 'layer2'
      this.origin = point
      this.paths.h1.layer = 'layer1'
      this.paths.w1.layer = 'layer2'
      this.paths.w1_2.layer = 'layer2'
      this.paths.w1_1.layer = 'layer2'
      this.models.textW.layer = 'layer1'
      this.models.textH.layer = 'layer2'
      this.models.text_1.layer = 'green'
    
      if(!index.includes('0')){
        delete this.models.textW
        delete this.paths.h1
        delete this.models.Ar2
        delete this.models.Ar1
      }
    }

  }


  class TextFont {
    constructor({ text, fontSize, point }) {
      this.models = {
        outer: new makerjs.models.Text(fonts.value, text, fontSize)
      }
      this.origin = point
    }

  }


  class ClosePath {
    constructor({ points, point }) {
      this.models = {
        outer: new makerjs.models.ConnectTheDots(true, points)
      }
      this.origin = point
    }

  }


  let calculateTrapezoidPoints = (baseTop, baseBottom, height) => {
    // 计算下底的两个端点
    const pointA = {
      x: -baseBottom / 2,
      y: 0
    };
    const pointB = {
      x: baseBottom / 2,
      y: 0
    };

    // 计算上底的两个端点
    const pointC = {
      x: baseTop / 2,
      y: height
    };
    const pointD = {
      x: -baseTop / 2,
      y: height
    };

    // 返回坐标点数组
    return [pointA.x, pointA.y, pointB.x, pointB.y, pointC.x, pointC.y, pointD.x, pointD.y];
  }



  function debounce(fn, delay = 500) {
    // timer 是在闭包中的
    let timer = null;

    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      
      timer = setTimeout(() => {
        fn.apply(this, arguments)
        timer = null
      }, delay)
    }
  }



  let propsFn = (propsObj) => {
    // if(!fonts.value) return
   
    if (true) {
      model.value = {
        paths: {
          // line1: new makerjs.paths.Line([-propsObj.Xlength, 0], [propsObj.Xlength, 0]),
          // line2: new makerjs.paths.Line([0, -propsObj.Ylength], [0, propsObj.Ylength]),

        },
        models: {
          // TextFont1: new TextFont({ text: 'X', fontSize: 5, point: [propsObj.Xlength + 2, -1] }),
          // TextFont2: new TextFont({ text: 'Y', fontSize: 5, point: [-1, propsObj.Ylength + 2] }),
        

          // box8:new rectangleBox({width:20,height:10,point:[0,0]}),
          // box10:new rectangleBox({width:20,height:10,point:[5,0]}),
          // box2: new rectangleBox({width:20,height:10,point:[0,10]}),
          // box3: new ClosePath({points:calculateTrapezoidPoints(10,20,10).flat().toString(),point:[0,20]}),
          // box4: new rectangleBox({width:10,height:10,point:[0,30]})
        }
      }
      // makerjs.model.combine(model.value.models.box8,model.value.models.box10,true,true,false,true)
      // console.log(model.value.models.box8)
      // console.log(model.value.models.box10.models.outer.paths)
      for (let i in propsObj.render) {
        if(i.includes('筒体')){
          model.value.models[`${i}`] = new rectangleBox({ 
          index:i,
          width: propsObj.render[i].width, 
          height: propsObj.render[i].height, 
          point: propsObj.render[i].point, 
          text1: propsObj.render[i].thickness_TEXT })
      }
          
       }
       




      // model.value.models.TextFont1.layer = "red";
      // model.value.models.TextFont2.layer = "green";
      // model.value.paths.line1.layer = "red";
      // model.value.paths.line2.layer = "green";
      renderHtml(model.value)

      console.log(model.value)

    }





  }





  let de = debounce(propsFn, 1000)
  watch(() => props.propsObj, () => {
    
    if (Object.keys(props.propsObj).length > 0) {
      de(props.propsObj)
    } else {
      document.querySelector('#CAD').innerHTML = '';
    }


  }, { deep: true })







  let initSvg = (reanderModel) => {

    loadingCad.value = true
    document.querySelector('#CAD').innerHTML = ''
    return new Promise((resolve) => {
    
      var svg = makerjs.exporter.toSVG(reanderModel, {
        viewBox: false,
        strokeWidth: '1.5',   // 统一线条粗细
        className: 'my_svg',
        annotate: true,
        layerOptions:{
          layer1:{
            fill:'yellow',
            stroke:'yellow'
          },
          layer2:{
            fill:'blue',
            stroke:'blue'

          },
          layer3:{
            stroke:'red',
            strokeWidth:'2.1',
          }
        },
        fillRule: 'evenodd'
      });



      resolve(svg)

    })

  }


  let renderHtml = async (reanderModel) => {
    try{
      let res = await initSvg(reanderModel)

   if (!res.includes('NaN')) {

  document.querySelector('#CAD').innerHTML = res;
  document.querySelector('#CAD').childNodes.forEach((V, i) => {
    V.setAttribute(`id`, `id_${i}`)
    V.style.width = '95%'
    V.style.height = '95%'
  })

  console.log(document.querySelector('#id_0'))
  svgPanZoom(document.querySelector('#id_0'), {
    panEnabled: true,
    zoomEnabled: true,

    onPan: function () {
      console.log('Panning...');
    },
    onZoom: function () {
      console.log('Zooming...');
    }
  })
  loadingCad.value = false

}

    }catch(err){
      console.log(err)

    }
   

  }




  onBeforeMount(() => {
//  console.log(themeConfig.value.fonts)
    // fonts.value = inject('fonts_ttf')
    // console.log(fonts.value)
    // opentype.load('./SourceHanSans-VF.ttf', async function (err, font) {

    //   fonts.value = font
    //   console.log(fonts.value)

    // });
  })



</script>

<style>
  .CAD {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: -webkit-linear-gradient(top, transparent 39px, #404855 0), -webkit-linear-gradient(left, #32404c 39px, #404855 0);
    background-color: #32404e;
    background-size: 40px 40px;
  }
  #CAD{
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>